﻿using System;
using StubsDemo.SystemUnderTest;
using StubsDemo.SystemUnderTest.Fakes;
using StubsDemo.SystemUnderTest.ViewModels;
using Xunit;
using System.Linq;

public class CustomerViewModelTests
{
    [Fact]
    public void SaveShouldUpdateTheRepository()
    {
        // Arrange
        var savedCustomer = default(Customer); // null
        var repository = new StubICustomerRepository
                                {
                                    SaveOrUpdateCustomer = customer => savedCustomer = customer
                                };
        var actualCustomer = new Customer { Id = 1, Name = "Sample Customer" };
        var viewModel = new CustomerViewModel(actualCustomer, repository);

        // Act
        viewModel.Save();

        // Assert
        Assert.NotNull(savedCustomer);
        Assert.Equal(1, savedCustomer.Id);
        Assert.Equal("Sample Customer", savedCustomer.Name);
    }

    [Fact]
    public void SaveShouldSetTheCorrectLastUpdatedDate()
    {
        // Arrange
        var savedCustomer = default(Customer); // null
        var repository = new StubICustomerRepository();
		repository.SaveOrUpdateCustomer = customer => savedCustomer = customer;

        var actualCustomer = new Customer { Id = 1, Name = "Sample Customer", LastUpdated = DateTime.MinValue };
        var viewModel = new CustomerViewModel(actualCustomer, repository);

        // Act
        var now = DateTime.Now;
        viewModel.Save();

        // Assert
        Assert.NotNull(savedCustomer);

        var delta = Math.Abs((savedCustomer.LastUpdated - now).TotalMilliseconds);
        const int accuracy = 10; // milliseconds
        Assert.True(delta <= accuracy, "LastUpdated was not appx equal to expected");
    }
}